package com.tea.funct.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tea.common.annotation.Log;
import com.tea.common.core.controller.BaseController;
import com.tea.common.core.domain.AjaxResult;
import com.tea.common.core.page.TableDataInfo;
import com.tea.common.enums.BusinessType;
import com.tea.common.utils.StringUtils;
import com.tea.common.utils.file.FileUtils;
import com.tea.common.utils.poi.ExcelUtil;
import com.tea.funct.domain.TeaProduct;
import com.tea.funct.domain.test.ProductInfo;
import com.tea.funct.domain.test.Root;
import com.tea.funct.service.ITeaProductService;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * 产品管理Controller
 *
 * @author Sophia
 * @date 2024-05-25
 */
@Slf4j
@RestController
@RequestMapping("/funct/product")
public class TeaProductController extends BaseController {
    @Autowired
    private ITeaProductService teaProductService;

    /**
     * 查询产品管理列表
     */
    @PreAuthorize("@ss.hasPermi('funct:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(TeaProduct teaProduct) {
        startPage();
        List<TeaProduct> list = teaProductService.selectTeaProductList(teaProduct);
        return getDataTable(list);
    }

    /**
     * 查询所有产品管理列表
     */
    @PreAuthorize("@ss.hasPermi('funct:product:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll() {
        List<TeaProduct> list = teaProductService.selectTeaProductList(null);
        return getDataTable(list);
    }

    /**
     * 导出产品管理列表
     */
    @PreAuthorize("@ss.hasPermi('funct:product:export')")
    @Log(title = "产品管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TeaProduct teaProduct) {
        List<TeaProduct> list = teaProductService.selectTeaProductList(teaProduct);
        ExcelUtil<TeaProduct> util = new ExcelUtil<TeaProduct>(TeaProduct.class);
        util.exportExcel(response, list, "产品管理数据");
    }

    /**
     * 获取产品管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('funct:product:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(teaProductService.selectTeaProductById(id));
    }

    /**
     * 新增产品管理
     */
    @PreAuthorize("@ss.hasPermi('funct:product:add')")
    @Log(title = "产品管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TeaProduct teaProduct) {
        return toAjax(teaProductService.insertTeaProduct(teaProduct));
    }

    /**
     * 修改产品管理
     */
    @PreAuthorize("@ss.hasPermi('funct:product:edit')")
    @Log(title = "产品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TeaProduct teaProduct) {
        return toAjax(teaProductService.updateTeaProduct(teaProduct));
    }

    /**
     * 删除产品管理
     */
    @PreAuthorize("@ss.hasPermi('funct:product:remove')")
    @Log(title = "产品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(teaProductService.deleteTeaProductByIds(ids));
    }


    /**
     * 根据报文解析并更新产品信息
     *
     * @param str json报文信息
     * @return
     */
    @PutMapping("/updateProductByStr")
    @PreAuthorize("@ss.hasPermi('funct:product:edit')")
    public AjaxResult updateProductByStr(@RequestBody String str) {
        try {
            Date date = new Date(); // 获取当前时间
            log.info("手动更新产品数据...");
            if (StringUtils.isBlank(str)) {
                log.info("入参为空...");
                return AjaxResult.error("入参不能为空");
            }
            List<ProductInfo> pList = new ArrayList<>();
            // 处理JSON数据
            JSONObject jsonObject = JSONUtil.parseObj(str);
            JSONObject result = jsonObject.getJSONObject("result");
            Root root = JSONUtil.toBean(result, Root.class);
            List<ProductInfo> records = root.getRecords();
            log.info("信息:{}", records);
            pList.addAll(records);
            List<TeaProduct> teaProducts = new ArrayList<>();
            // 设置数据并更新入库
            if (pList != null && pList.size() > 0) {
                for (ProductInfo p : pList) {
                    TeaProduct teaProduct = new TeaProduct();
                    teaProduct.setProductPrice(p.getProductMoney() != null ? new BigDecimal(p.getProductMoney()) : null);
                    teaProduct.setGuidePrice(p.getGuidePrice() != null ? new BigDecimal(p.getGuidePrice()) : null);
                    teaProduct.setTradePrice(p.getTradePrice() != null ? new BigDecimal(p.getTradePrice()) : null);
                    teaProduct.setBiliPrice(p.getBili() != null ? new BigDecimal(p.getBili()) : null);
                    if (StringUtils.isBlank(p.getBili()) || StringUtils.equals(p.getBili(), "0.0")) {
                        teaProduct.setBiliType("0"); // 0平，1涨，2降
                    } else {
                        teaProduct.setBiliType(p.getType()); // 1涨，2降
                    }
                    teaProduct.setProductFlagId(p.getProductId());
                    teaProduct.setCreateTime(date);
                    teaProduct.setUpdateTime(new Date());
                    teaProducts.add(teaProduct);
                }
            }
            if (teaProducts != null && teaProducts.size() > 0) {
                teaProductService.updateTeaProductAllByFlagId(teaProducts);
                log.info("数据批量修改完成!");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("json解析入库出现异常：{}", e.getMessage());
            log.error(e.getMessage(), e);
            return AjaxResult.error("json解析入库出现异常");
        }
    }

    /**
     * 根据文件解析报文信息
     *
     * @return
     */
    @PostMapping("/updateProductByFile")
    @PreAuthorize("@ss.hasPermi('funct:product:edit')")
    public AjaxResult updateProductByFile(MultipartFile multFile) {
        log.info("解析XML文件并更新产品信息...");
        try {
            Date date = new Date(); // 获取当前时间
            // 创建Reader对象
            SAXReader reader = new SAXReader();
            File file = FileUtils.multipartFileToFile(multFile);
            // 加载xml
            Document document = reader.read(file);
            // 获取根节点
            Element rootElement = document.getRootElement();
            Iterator iterator = rootElement.elementIterator();
            List<String> list = new ArrayList<>();

            while (iterator.hasNext()) {
                Element stu = (Element) iterator.next();
                List<Attribute> attributes = stu.attributes();
                log.info("======获取属性值======");
                for (Attribute attribute : attributes) {
                    log.info(attribute.getValue());
                }
                log.info("======遍历子节点======");
                Iterator iterator1 = stu.elementIterator();
                while (iterator1.hasNext()) {
                    Element stuChild = (Element) iterator1.next();
                    log.info("节点名：" + stuChild.getName() + "---节点值：" + stuChild.getStringValue());
                    if (StringUtils.equals(stuChild.getName(), "response")) {
                        list.add(stuChild.getStringValue());
                    }
                }
            }
            List<String> jsonList = new ArrayList<>();
            // Base64解析
            if (list != null && list.size() > 0) {
                for (String s : list) {
                    byte[] decode = Base64.getDecoder().decode(s);
                    String resp = new String(decode);
                    String start = "{\"success\"";
                    // 获取开始子串的索引
                    int index = resp.indexOf(start);
                    if (index != -1) {
                        // 从开始子串结束的位置开始截取，直到字符串末尾
                        resp = start + resp.substring(index + start.length());
                    }
                    jsonList.add(resp);
                }
            }
            List<ProductInfo> pList = new ArrayList<>();
            // 处理JSON数据
            if (jsonList != null && jsonList.size() > 0) {
                for (String json : jsonList) {
                    JSONObject jsonObject = JSONUtil.parseObj(json);
                    JSONObject result = jsonObject.getJSONObject("result");
                    Root root = JSONUtil.toBean(result, Root.class);
                    List<ProductInfo> records = root.getRecords();
                    log.info("信息:{}", records);
                    pList.addAll(records);
                }
            }
            List<TeaProduct> teaProducts = new ArrayList<>();
            // 设置数据并更新入库
            if (pList != null && pList.size() > 0) {
                for (ProductInfo p : pList) {
                    TeaProduct teaProduct = new TeaProduct();
                    teaProduct.setProductPrice(p.getProductMoney() != null ? new BigDecimal(p.getProductMoney()) : null);
                    teaProduct.setGuidePrice(p.getGuidePrice() != null ? new BigDecimal(p.getGuidePrice()) : null);
                    teaProduct.setTradePrice(p.getTradePrice() != null ? new BigDecimal(p.getTradePrice()) : null);
                    teaProduct.setBiliPrice(p.getBili() != null ? new BigDecimal(p.getBili()) : null);
                    if (StringUtils.isBlank(p.getBili()) || StringUtils.equals(p.getBili(), "0.0")) {
                        teaProduct.setBiliType("0"); // 0平，1涨，2降
                    } else {
                        teaProduct.setBiliType(p.getType()); // 1涨，2降
                    }
                    teaProduct.setProductFlagId(p.getProductId());
                    teaProduct.setCreateTime(date);
                    teaProduct.setUpdateTime(new Date());
                    teaProducts.add(teaProduct);
                }
            }
            if (teaProducts != null && teaProducts.size() > 0) {
                teaProductService.updateTeaProductAllByFlagId(teaProducts);
                log.info("数据批量修改完成!");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("文件解析入库出现异常：{}", e.getMessage());
            log.error(e.getMessage(), e);
            return AjaxResult.error("文件解析入库出现异常");
        }
    }

}
